package com.xbongbong.paas.script.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xbongbong.paas.domain.entity.ext.PaasFormDataEntityExt;
import com.xbongbong.paas.elasticsearch.util.EsHelper;
import com.xbongbong.paas.elasticsearch.util.EsUtil;
import com.xbongbong.paas.elasticsearch.util.XbbElasticsearchRestTemplate;
import com.xbongbong.paas.enums.DelEnum;
import com.xbongbong.paas.enums.IndexTypeEnum;
import com.xbongbong.paas.pojo.dto.FixDataJobDTO;
import com.xbongbong.paas.script.help.ScriptEsHelper;
import com.xbongbong.paas.script.pojo.ListVO;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.util.StringUtil;
import com.xbongbong.paas.util.ExplainUtil;
import com.xbongbong.pro.config.ProBaseConfig;
import com.xbongbong.pro.constant.XbbProConstant;
import com.xbongbong.pro.domain.entity.UpdateDataEntity;
import com.xbongbong.pro.enums.errorcodes.SystemErrorCodeEnum;
import com.xbongbong.saas.constant.StringConstant;
import com.xbongbong.saas.enums.business.ClueEnum;
import com.xbongbong.saas.enums.business.ContractEnum;
import com.xbongbong.saas.enums.business.CustomerManagementEnum;
import com.xbongbong.saas.enums.business.SalesOpportunityEnum;
import com.xbongbong.saas.model.ContractModel;
import com.xbongbong.saas.model.CustomerModel;
import com.xbongbong.saas.model.OpportunityModel;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.domain.PageRequest;
import org.springframework.http.MediaType;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.function.Function;
import java.util.stream.Collectors;

import static org.elasticsearch.index.query.QueryBuilders.termQuery;
import static org.elasticsearch.index.query.QueryBuilders.termsQuery;

@RestController
@RequestMapping(XbbProConstant.API_ROOT_PREFIX + "/sdrScript")
public class SdrScriptController {
    @Resource
    private ProBaseConfig proBaseConfig;
    @Resource
    private XbbElasticsearchRestTemplate xbbElasticsearchRestTemplate;
    @Resource
    private ScriptEsHelper scriptEsHelper;
    @Resource
    private EsHelper esHelper;
    @Resource
    private CustomerModel customerModel;
    @Resource
    private ContractModel contractModel;
    @Resource
    private OpportunityModel opportunityModel;

    private static final Logger LOG = LoggerFactory.getLogger(SdrScriptController.class);


    @RequestMapping(value = "/clueInfo", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public String clueInfo(@RequestBody @Valid FixDataJobDTO fixDataJobDTO, BindingResult br) throws Exception {
        if (!proBaseConfig.getXbbCode().equals(fixDataJobDTO.getXbbCode())) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100006, SystemErrorCodeEnum.API_ERROR_100006.getMsg());
        }
        LOG.info("clueInfo start");
        String corpid = "dinge3fa697f86d461d2";
        BoolQueryBuilder boolQueryBuilder = new BoolQueryBuilder();
        boolQueryBuilder.filter(termQuery(StringConstant.CORPID + StringConstant.POINT + StringConstant.KEY_WORD, corpid));
        boolQueryBuilder.filter(termQuery(ClueEnum.getEsAttr4Keyword(ClueEnum.CLUE_STAGE), "6a789226bad14eb2b17c65be11c1a37c"));
        boolQueryBuilder.filter(termQuery(StringConstant.DEL, DelEnum.NORMAL.getDel()));
        Long dataDataMark = 0L;
        Map<String, String> userMap = new HashMap<>();
        userMap.put("6e12b5e6-fdc0-f9b3-02f9-25116cd81194", "1-19人");
        userMap.put("d4d39951-f5a7-34c8-6969-e6dd183c479a", "20-49人");
        userMap.put("184b4887-4695-1a03-b176-f553e0193e60", "50-99人");
        userMap.put("036f39d4-a62d-01f7-a8a6-85098fa21b2c", "100-199人");
        userMap.put("683f779b-1dc5-12e3-09fb-44c50fa5f71e", "200-499人");
        userMap.put("f4ad7834-50ba-9f94-115d-518091c0288c", "500人以上");
        int total = 9009;
        int page = 1;
        while (true) {
            ListVO listVO = scriptEsHelper.list(boolQueryBuilder, 100, PaasFormDataEntityExt.class, IndexTypeEnum.IDX_SAAS_CLUE, dataDataMark);
            List<PaasFormDataEntityExt> list = listVO.getList();
            dataDataMark = listVO.getDataIdMark();
            if (list.isEmpty()) {
                break;
            }
            LOG.info("clueInfo ing:{}/{}", page * 100, total);
            page++;
            Map<Long, PaasFormDataEntityExt> clueMap = list.stream().collect(Collectors.toMap(PaasFormDataEntityExt::getId, Function.identity()));
            BoolQueryBuilder customerBoolQuery = new BoolQueryBuilder();
            customerBoolQuery.filter(termQuery(StringConstant.CORPID + StringConstant.POINT + StringConstant.KEY_WORD, corpid));
            customerBoolQuery.filter(termsQuery(CustomerManagementEnum.getEsAttr4Keyword(CustomerManagementEnum.CLUE_ID), clueMap.keySet()));
            customerBoolQuery.filter(termQuery(StringConstant.DEL, DelEnum.NORMAL.getDel()));
            SearchRequest searchRequest = new SearchRequest(IndexTypeEnum.IDX_SAAS_CUSTOMER.getIndex());
            SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
            sourceBuilder.query(customerBoolQuery);
            searchRequest.source(sourceBuilder);
            PageRequest pageRequest = EsUtil.setPage(sourceBuilder, 0, 1000);
            List<PaasFormDataEntityExt> customerList = xbbElasticsearchRestTemplate.queryForPages(pageRequest, searchRequest, PaasFormDataEntityExt.class).getContent();
            if (!customerList.isEmpty()) {
                List<UpdateDataEntity> customerUpdateList = new ArrayList<>();
                List<UpdateDataEntity> contractUpdateList = new ArrayList<>();
                List<UpdateDataEntity> opportunityUpdateList = new ArrayList<>();
                Map<Long, Long> idMap = new HashMap<>();
                for (PaasFormDataEntityExt paasFormDataEntityExt : customerList) {
//                    if (clueMap.containsKey(paasFormDataEntityExt.getId())) {
//                        PaasFormDataEntityExt clue = clueMap.get(paasFormDataEntityExt.getId());
//                        if (Objects.nonNull(clue.getData().get("date_6"))) {
//                            JSONObject data = new JSONObject();
//                            data.put("date_11", clue.getData().get("date_6"));
//                            UpdateDataEntity updateDataEntity = ExplainUtil.getUpdateData(paasFormDataEntityExt.getId(), data,corpid);
//                            customerUpdateList.add(updateDataEntity);
//                        }
//                    }
                    try {
                        List<Long> clueIdArray = JSONArray.parseArray(paasFormDataEntityExt.getData().getString(CustomerManagementEnum.CLUE_ID.getAttr())).toJavaList(Long.class);
                        if (!clueIdArray.isEmpty()) {
                            idMap.put(paasFormDataEntityExt.getId(), clueIdArray.get(0));
                        }
                    } catch (Exception e) {
                        LOG.info("error1:{}", paasFormDataEntityExt.getId());
                    }
                }
                List<Long> customerIdList = customerList.stream().map(PaasFormDataEntityExt::getId).collect(Collectors.toList());
                //查合同
                BoolQueryBuilder contractBoolQuery = new BoolQueryBuilder();/*
                contractBoolQuery.filter(termQuery(StringConstant.CORPID + StringConstant.POINT + StringConstant.KEY_WORD, corpid));
                contractBoolQuery.filter(termsQuery(ContractEnum.getEsAttr4Keyword(ContractEnum.LINK_CUSTOMER), customerIdList));
                contractBoolQuery.filter(termQuery(StringConstant.DEL, DelEnum.NORMAL.getDel()));
                searchRequest = new SearchRequest(IndexTypeEnum.IDX_SAAS_CONTRACT.getIndex());
                sourceBuilder = new SearchSourceBuilder();
                sourceBuilder.query(contractBoolQuery);
                searchRequest.source(sourceBuilder);
                List<PaasFormDataEntityExt> contractList = xbbElasticsearchRestTemplate.queryForPages(pageRequest, searchRequest, PaasFormDataEntityExt.class).getContent();
                for (PaasFormDataEntityExt paasFormDataEntityExt : contractList) {
                    Long clueId = idMap.get(paasFormDataEntityExt.getData().getLong(ContractEnum.LINK_CUSTOMER.getAttr()));
                    PaasFormDataEntityExt clue = clueMap.get(clueId);
                    if (Objects.nonNull(clue)) {
                        if (Objects.nonNull(clue.getData().get("text_12")) && StringUtil.isEmpty(paasFormDataEntityExt.getData().getString("text_39"))) {
                            JSONObject data = new JSONObject();
                            data.put("text_39", userMap.getOrDefault(clue.getData().getString("text_12"), clue.getData().getString("text_12")));
                            UpdateDataEntity updateDataEntity = ExplainUtil.getUpdateData(paasFormDataEntityExt.getId(), data,corpid);
                            contractUpdateList.add(updateDataEntity);
                        }
                    } else {
                        LOG.info("error2:{},{}", paasFormDataEntityExt.getId(), paasFormDataEntityExt.getData().getLong(ContractEnum.LINK_CUSTOMER.getAttr()));
                    }
                }*/
                //查机会
                BoolQueryBuilder opportunityBoolQuery = new BoolQueryBuilder();
                opportunityBoolQuery.filter(termQuery(StringConstant.CORPID + StringConstant.POINT + StringConstant.KEY_WORD, corpid));
                opportunityBoolQuery.filter(termsQuery(SalesOpportunityEnum.getEsAttr4Keyword(SalesOpportunityEnum.CUSTOMER_NAME), customerIdList));
                opportunityBoolQuery.filter(termQuery("formId", 1795141));
                opportunityBoolQuery.filter(termQuery(StringConstant.DEL, DelEnum.NORMAL.getDel()));
                searchRequest = new SearchRequest(IndexTypeEnum.IDX_SAAS_OPPORTUNITY.getIndex());
                sourceBuilder = new SearchSourceBuilder();
                sourceBuilder.query(opportunityBoolQuery);
                searchRequest.source(sourceBuilder);
                List<PaasFormDataEntityExt> opportunityList = xbbElasticsearchRestTemplate.queryForPages(pageRequest, searchRequest, PaasFormDataEntityExt.class).getContent();
                for (PaasFormDataEntityExt paasFormDataEntityExt : opportunityList) {
                    Long clueId = idMap.get(paasFormDataEntityExt.getData().getLong(SalesOpportunityEnum.CUSTOMER_NAME.getAttr()));
                    PaasFormDataEntityExt clue = clueMap.get(clueId);
                    if (Objects.nonNull(clue)) {
                        if (StringUtil.isEmpty(paasFormDataEntityExt.getData().getString("text_76"))
                            && StringUtil.isNotEmpty(clue.getData().getString("text_12"))) {
                            JSONObject data = new JSONObject();
                            data.put("text_76", userMap.getOrDefault(clue.getData().getString("text_12"), clue.getData().getString("text_12")));
                            UpdateDataEntity updateDataEntity = ExplainUtil.getUpdateData(paasFormDataEntityExt.getId(), data,corpid);
                            opportunityUpdateList.add(updateDataEntity);
                        }
//                        if (Objects.nonNull(clue.getData().get("date_6"))) {
//                            JSONObject data = new JSONObject();
//                            data.put("date_6", clue.getData().get("date_6"));
//                            UpdateDataEntity updateDataEntity = ExplainUtil.getUpdateData(paasFormDataEntityExt.getId(), data,corpid);
//                            opportunityUpdateList.add(updateDataEntity);
//                        }

                    } else {
                        LOG.info("error3:{},{}", paasFormDataEntityExt.getId(), paasFormDataEntityExt.getData().getLong(SalesOpportunityEnum.CUSTOMER_NAME.getAttr()));
                    }
                }
                //客户更新时间
                if (!customerUpdateList.isEmpty()) {
//                    customerModel.updateBatch(customerUpdateList, corpid);
                }
                //机会更新时间
                if (!opportunityUpdateList.isEmpty()) {
                    opportunityModel.updateBatch(opportunityUpdateList, corpid);
                }
                //合同更新规模
                if (!contractUpdateList.isEmpty()) {
//                    contractModel.updateBatch(contractUpdateList, corpid);
                }
            }
        }
        LOG.info("clueInfo over");
        return null;
    }
}
